package com.losdun.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/11/21
 **/
@Configuration
@EnableAsync
public class AsyncConfig {
    /**
     * 核心线程数（默认CPU核心数）
     */
    private int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 最大线程数
     */
    private int maxPoolSize = corePoolSize * 2;
    /**
     * 队列容量
     */
    private int queueCapacity = 100;
    /**
     * 线程空闲时间（秒）
     */
    private int keepAliveSeconds = 60;
    /**
     * 线程池前缀名
     */
    private String threadNamePrefix = "ruoyi-async-";

    /**
     * 自定义异步线程池
     */
    @Bean(name = "asyncExecutor") // 线程池名称，@Async可指定
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);

        // 拒绝策略：当线程池满时，由调用方线程执行（避免任务丢失）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        executor.initialize();
        return executor;
    }
}
